<template>
  <el-popover class="ai-popover" :visible="visible" placement="bottom" :width="390">
    <div v ref="scrollContainerRef" v-html="aiMsgRef"
      style="padding: 20px;max-height: 200px;overflow: auto; background-color: var(--el-color-success-light-8);border-radius: 1em;">
    </div>
    <template #reference>
      <el-button style="margin-left: 8px;" :loading="isLoadingAiRef" @click="doAiCompleteForm()" size="small" circle
        type="success" icon="MagicStick"></el-button>
    </template>
  </el-popover>
  <ai_msg ref="aiRef" :is-show-msg="false" :start-handle="aiStartHandle" :end-handle="aiEndHandle">
  </ai_msg>
</template>
<script setup lang="ts">
import farmHtmlUtils from '@/hook/farmHtmlUtils';
import type { SendMsg } from '@/types/ai/SendMsg';
import { nextTick, ref } from 'vue'
import ai_msg from './ai_msg.vue';
const visible = ref(false);
const isLoadingAiRef = ref(false);
const aiRef = ref();
const aiMsgRef = ref('');
const scrollContainerRef = ref<HTMLElement | null>(null); // 引用 div 元素
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

const props = defineProps({
  setFormValueHandle: {
    type: Function,
    required: true
  },
  getQuoteHtmlHandle: {
    type: Function,
    required: true
  },
  tip: {
    type: String,
    required: true
  }
});
/**
 * AI完善表单
 */
const doAiCompleteForm = () => {
  const msg = {
    msg: props.tip,
    quotingText: farmHtmlUtils.getMarkDown(props.getQuoteHtmlHandle()),
    msgType: 'FORM_COMPLETION',
  } as SendMsg;
  aiRef.value.senMsg(msg, (text: string, html: string) => {
    aiMsgRef.value = (html);
    scrollToBottom(); // 更新内容后立即滚动到底部
  });
}

const aiStartHandle = () => {
  isLoadingAiRef.value = true;
  visible.value = true;
  aiMsgRef.value = '...';
}
const aiEndHandle = () => {
  isLoadingAiRef.value = false;
  visible.value = false;
  if (!aiMsgRef.value) {
    aiMsgRef.value = "";
  }
  const backmsg = farmHtmlUtils.removeHtmltags(aiMsgRef.value.replace(/<div\s+class="think">\s*.*?<\/div>/gs, '')).trim();
  props.setFormValueHandle(backmsg.replaceAll('&quot;', "\""));
}
// 滚动到底部的方法
const scrollToBottom = () => {
  nextTick(() => { // 确保 DOM 已更新
    if (scrollContainerRef.value) {
      scrollContainerRef.value.scrollTop = scrollContainerRef.value.scrollHeight; // 设置 scrollTop 为最大值
    }
  });
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
</script>
<style scoped>
/* 样式可以根据需要添加 */
</style>
